import time

import uvicorn
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from pydantic import BaseModel

from api.routers import router
from utils import logger
from exceptions import APIException
from items.http_api_response import HTTPApiResponse
from config import settings

app = FastAPI()

app.include_router(router)

app.add_middleware(
    CORSMiddleware,
    allow_origins=['*'],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


# def init():
#     async def run_spider():
#         ...
#     return run_spider
#
#
# app.add_event_handler('startup', init())


@app.middleware('http')
async def http_interceptor(request: Request, call_next):
    try:
        start_time = time.time()
        response = await call_next(request)
        process_time = time.time() - start_time
        response.headers["X-Process-Time"] = str(process_time)
        return response
    except APIException as e:
        return JSONResponse(HTTPApiResponse.failed(e.state, e.msg).dict())
    except Exception as e:
        logger.exception(e)
        return JSONResponse(HTTPApiResponse.failed(30, f"发生未知异常{str(e)}").dict())


@app.get("/")
async def get_index(name=""):
    return HTTPApiResponse.success(f"hello {name}!")


class PostIndexItem(BaseModel):
    name: str


@app.post("/")
async def post_index(item: PostIndexItem):
    return HTTPApiResponse.success(f"hello {item.name}!")


if __name__ == '__main__':
    uvicorn.run('main:app', host='0.0.0.0', loop='asyncio', port=settings.app_port)
